package com.interview.rtc.aigc.utils;

import com.interview.rtc.aigc.dao.UserDao;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret:rtcaigcdemosecret}")
    private String secret;

    @Value("${jwt.expiration:86400}")
    private Long expiration; // 默认30天过期，在application.yml中配置为2592000秒

    // 从token中获取用户ID
    public Long getUserIdFromToken(String token) {
        return Long.parseLong(getClaimFromToken(token, Claims::getSubject));
    }

    // 获取token过期时间
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    // 从token中获取claims
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    // 解析token获取所有claims
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    // 检查token是否过期
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    // 检查token是否即将过期（如果剩余有效期小于给定的阈值）
    public Boolean isTokenNearExpiration(String token, long thresholdSeconds) {
        final Date expiration = getExpirationDateFromToken(token);
        final Date now = new Date();
        // 计算剩余有效期（毫秒）
        long timeToExpire = expiration.getTime() - now.getTime();
        // 转换为秒并与阈值比较
        return (timeToExpire / 1000) < thresholdSeconds;
    }

    // 为UserDao对象生成token
    public String generateToken(UserDao user) {
        return generateToken(user.getId(), user.getUsername());
    }

    // 为指定用户ID生成token
    public String generateToken(Long userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        return doGenerateToken(claims, userId.toString());
    }

    // 刷新token
    public String refreshToken(String token) {
        try {
            // 从旧token中获取claims
            final Claims claims = getAllClaimsFromToken(token);
            // 获取用户ID
            String userId = claims.getSubject();
            // 获取用户名
            String username = (String) claims.get("username");
            // 生成新token
            return doGenerateToken(claims, userId);
        } catch (Exception e) {
            return null;
        }
    }

    // 生成token
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = new Date();
        final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 验证token
    public Boolean validateToken(String token) {
        return !isTokenExpired(token);
    }
} 